﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using SalePartial.BLL;
using SalePartial.Model;
using SalePartial.Utility;
using XunPan.Web.Globals;
using System.IO;
using System.Data;

public partial class Trade_Events_event_item : System.Web.UI.Page
{
    protected void Page_Load(object sender, System.EventArgs e)
    {
        if (!IsPostBack)
        {

            ////■■■■■テストため■■■■
            //UserBLL.StoreUserInfoToSession("j@j10.com");
            LoginUserType type = RoleControlManager.checkUserAuthority(User.Identity.Name);
            if (type == LoginUserType.FREE_SUPPLY
                || type == LoginUserType.CERT_SUPPLY || type == LoginUserType.CERT_SUP_PUR
                || type == LoginUserType.FREE_SUP_PUR)
            {
                if (HttpContext.Current.Session["EventID"] != null)
                {
                    string eventid = (string)HttpContext.Current.Session["EventID"];
                    ltrEventID.Text = eventid;
                    XPInquiryEvent xpInqu = new XPInquiryEvent();
                    XPInquiryEventInfo xpevent = xpInqu.GetXPInquiryEvent(new Guid(eventid));

                    SqlDataSource1.SelectParameters["InquiryID"].DefaultValue = xpevent.InquiryID.ToString();
                    MembershipUserCollection userList = Membership.FindUsersByEmail(User.Identity.Name);
                    if (userList == null)
                    {
                        Response.Redirect(GlobalSetting.UrlHomePage, true);
                    }
                    //SqlDataSource1.SelectParameters["UserID"].DefaultValue = Session["UserID"].ToString();
                    SqlDataSource1.SelectParameters["gysid"].DefaultValue = Session["UserID"].ToString();

                    SqlDataSource2.SelectParameters["InquiryID"].DefaultValue = xpevent.InquiryID.ToString();


                }

                //SqlDataSource1.SelectParameters("InquiryID").DefaultValue = "bfab11b4-b021-4347-824d-26b33c7b733a"
                //SqlDataSource2.SelectParameters("InquiryID").DefaultValue = "bfab11b4-b021-4347-824d-26b33c7b733a"
            }
            else
            {
                Response.Redirect(GlobalSetting.UrlHomePage, true);

            }
        }
    }

    protected string GetCurrencyName(string code)
    {
        //FIXME:
        return GlobalUtility.ParseCurrencyCode(code,null);
    }
    protected string GetProcessName(string code, int type)
    {
        //FIXME:
        return GlobalUtility.ParseProcessCode(code, type, null);
    }

    protected void rptBindInquiry_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
    {
        switch (e.CommandName.ToLower())
        {
            case "quote":
                string inquiryid = e.CommandArgument.ToString();

                HttpContext.Current.Session["InquiryID"]= inquiryid;
                Response.Redirect("~/Trade/Supplier/SupplierQuote.aspx");
                break;
            //HttpContext.Current.Response.Redirect("~/Trade/trade_quote.aspx", True)
            case "feedback":
                pnlFeedback.Visible = true;
                lbtSubmitFeedback.CommandArgument = (string)e.CommandArgument;
                break;
            case "loaddwg":
                string filepath = Server.MapPath((string)e.CommandArgument);



                if (File.Exists(filepath))
                {
                    string fileName = Path.GetFileName(filepath);
                    FileStream MyFileStream = new FileStream(filepath, FileMode.Open);
                    long fileSize = MyFileStream.Length;
                    Context.Server.ScriptTimeout = 600;
                    Context.Response.Buffer = true;
                    Context.Response.Clear();
                    Context.Response.ContentType = "application/octet-stream";
                    Context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\";");
                    Context.Response.AddHeader("Content-Length", Convert.ToInt32(fileSize).ToString());
                    byte[] fileBuffer = new byte[Convert.ToInt32(fileSize) + 1];
                    MyFileStream.Read(fileBuffer, 0, Convert.ToInt32(fileSize));
                    MyFileStream.Close();

                    Context.Response.BinaryWrite(fileBuffer);

                    // End the response
                    Context.Response.End();
                }
                break;
        }


    }

    protected void radGridMainList_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        if (e.CommandName == "EditQuote" && !string.IsNullOrEmpty(e.CommandArgument.ToString()))
        {
            //HttpContext.Current.Items.Add("InquiryID", SqlDataSource1.SelectParameters("InquiryID").DefaultValue)
            //Dim p As String = e.CommandArgument.ToString
            //Trace.Warn(p)
            HttpContext.Current.Session["InquiryID"] = SqlDataSource1.SelectParameters["InquiryID"].DefaultValue;
            HttpContext.Current.Session["QuoteID"] =  e.CommandArgument.ToString();
            Response.Redirect("~/Trade/Supplier/SupplierQuote.aspx");
        }
        else if (e.CommandName == "EditRating" && !string.IsNullOrEmpty(e.CommandArgument.ToString()))
        {
            pnlFeedback.Visible = true;
            lbtSubmitFeedback.CommandArgument = (string)e.CommandArgument;
        }

    }

    protected bool EnableQuote(string istatus)
    {
        bool enable = false;
        try
        {
            //检查已授盘状态
            if (istatus.Substring(4, 1) == "0")
            {
                enable = true;
            }
        }
        catch (Exception ex)
        {
            enable = false;
        }

        return enable;

    }

    protected bool EnableEditQuote(string istatus)
    {
        bool enable = false;
        try
        {
            //检查未提交状态
            if (istatus.StartsWith("10"))
            {
                enable = true;
            }
            //检查(供应商)未反馈状态
            else if (istatus.Substring(3, 1) == "1" &&
                istatus.Substring(5, 1) == "0")
            {
                enable = true;
            }
        }
        catch (Exception ex)
        {
            enable = false;
        }

        return enable;

    }

    protected string GetEditQuoteText(string istatus, string type)
    {
        string text = "";
        try
        {
            //检查未提交状态
            if (istatus.StartsWith("10"))
            {
                if (type == "CommandName")
                {
                    text = "EditQuote";
                }
                else if (type == "Text")
                {
                    text = "编辑";
                }
            }
            //检查(供应商)未反馈状态
            else if (istatus.Substring(3, 1) == "1" &&
                istatus.Substring(5, 1) == "0")
            {
                if (type == "CommandName")
                {
                    text = "EditRating";
                }
                else if (type == "Text")
                {
                text = "评价采购商";
                }
            }
        }
        catch (Exception ex)
        {
            //enable = false;
        }

        return text;

    }


    protected bool EnableVendorFeedback(string inquiryid)
    {
        bool enable = false;
        if (GlobalUtility.IsValidGuid(inquiryid))
        {
            try
            {
                //if (Session["s_userID_guid"] == null || Session["s_companyID_guid"] == null)
                //{
                //    bool result = UserBLL.StoreUserInfoToSession(User.Identity.Name);
                //}
                //Guid companyid = new Guid((string)Session["s_companyID_guid"]);

                ////Dim dt As DataTable = XPQuoteUtility.SelectByInquiryID(New Guid(inquiryid)).Tables(0)
                //DataTable dt = new DataTable();

                //DataView dv = dt.DefaultView;
                //dv.RowFilter = string.Format("[CompanyID] = '{0}'", companyid.ToString());

                //for (int i = 0; i <= dv.Count - 1; i++)
                //{
                //    dynamic qstatus = dv[i]["QuoteStatus"].ToString();
                //    if (qstatus.Substring(3, 1) == "1" && qstatus.Substring(5, 1) == "0")
                //    {
                //        lbtSubmitFeedback.CommandName = dv[i]["QuoteID"].ToString();

                //        enable = true;
                //        break; // TODO: might not be correct. Was : Exit For
                //    }
                //}
                XPInquiryEvent xpInquEvt = new XPInquiryEvent();
                XPInquiryEventInfo xpevent = xpInquEvt.GetXPInquiryEvent(new Guid(ltrEventID.Text));
                if (xpevent != null)
                {
                    if (xpevent.EventStatus.Substring(1, 3) == "110")
                    {
                        enable = true;
                    }
                }

                //检查已授盘状态和未反馈状态

            }
            catch (Exception ex)
            {
                enable = false;
            }
        }

        return enable;

    }
    protected string ParseQuoteStatus(string qstatus)
    {
        string display = "";
        try
        {
            //检查提交状态
            if (qstatus.Substring(1, 1) == "1")
            {
                display += "已提交/";
            }
            else
            {
                display += "未提交/";
            }
            //检查授盘状态
            if (qstatus.Substring(3, 1) == "1")
            {
                display += "已授盘/";
                //反馈状态
                if (qstatus.Substring(5, 1) == "1")
                {
                    display += "已评价/";
                }
                else
                {
                    display += "等待评价/";
                }
            }

            if (display.EndsWith("/"))
            {
                display = display.TrimEnd("/".ToCharArray());
            }
        }
        catch (Exception ex)
        {
            display = "未知";
        }

        return display;

    }

    protected void lbtSubmitFeedback_Click(object sender, System.EventArgs e)
    {
       
        string xpid = lbtSubmitFeedback.CommandArgument;
       // string qid =  lbtFeedback.CommandArgument;

        XPInquiry xpInquiry = new XPInquiry();
        XPInquiryInfo inquiry = xpInquiry.GetXPInquiry(new Guid(xpid));
        XPRating xpRating = new XPRating();
        XPRatingInfo rating = new XPRatingInfo();
        XPInquiryEvent xpInqu = new XPInquiryEvent();
        DataSet ds = xpInqu.SelectByInquiryID(new Guid(xpid));
        var _with1 = rating;

        _with1.RatingSubject = 3;
        //供应商
        _with1.RatingOwnerID = new Guid(xpid);
        //采购商
        _with1.RatingTargetID = new Guid(SqlDataSource1.SelectParameters["InquiryID"].DefaultValue);
        _with1.RatingComment = rtbRateComment.Text;
        _with1.RatingValue = Convert.ToInt16(rRatingFromBuyer.Value);


        try
        {

            if (_with1.RatingValue == -1 && string.IsNullOrEmpty(_with1.RatingComment))
            {
                Label msg = new Label();
                msg.Text = "请填写补充说明";
                msg.ForeColor = System.Drawing.Color.Red;

                phMessage.Controls.Add(msg);

            }
            else
            {
                xpRating.Insert(rating);

                //设置反馈状态
                XPQuote xpQuote = new XPQuote();
                XPQuoteInfo quote = xpQuote.GetXPQuote(_with1.RatingOwnerID);
               
                quote.QuoteStatus = quote.QuoteStatus.Remove(5, 1);
                quote.QuoteStatus = quote.QuoteStatus.Insert(5, "1");
                xpQuote.Update(quote);
                ds = xpInqu.SelectDynamic(string.Format("[VendorCompanyID] = '{0}' AND [InquiryID] = '{1}'", quote.CompanyID, quote.InquiryID), "");
                DataTable dt = ds.Tables[0];
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)

                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        XPInquiryEventInfo xpevent = xpInqu.GetXPInquiryEvent(new Guid(ds.Tables[0].Rows[i]["EventID"].ToString()));

                        xpevent.EventStatus = xpevent.EventStatus.Remove(3, 1);
                        xpevent.EventStatus = xpevent.EventStatus.Insert(3, "1");
                        xpInqu.Update(xpevent);
                    }
                    



                pnlFeedback.Visible = false;
                rptBindInquiry.DataBind();
                radGridMainList.Rebind();



               




                //发送系统邮件
                MembershipUser userInfo = Membership.GetUser(quote.UserID);
                if (userInfo != null)
                {
                    MailSendUtility.SyncSendMail(userInfo.Email, "零部件环球资源网--来自供应商的评价", "来自供应商的评价");
                }
                //消息
                XPNotificationInfo msg = new XPNotificationInfo();
                XPNotification xpNotifi = new XPNotification();

                msg.CreateUserID = new Guid(Session["UserId"].ToString());
                msg.Status = "0100000";
                msg.CreateDate = DateTime.Now;

                msg.RecipientUserID = new Guid(PUerid.Text) ;
                msg.Attachment = "";
                msg.BodyText = "尊敬的采购商：</br>" +
                Session["UserName"].ToString()+"供应商已经对您的询盘" + ltlPartName.Text +
                "进行了反馈评价，具体内容为：</br>" + "反馈结果：" + _with1.RatingValue + "<br>" +
                "补充信息：" + _with1.RatingComment + "</br>如果您还没有提交对供应商的反馈，" +
                "请进入询盘填写提交。您的反馈评价非常重要，将有助于建立平台良好的信用体系。</br>"
                  + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;谢谢!</br>"
                  + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Fsafdsa网站客服";
                msg.SendDate = DateTime.Now;
                msg.Title = "零部件环球资源网--来自供应商的评价";

                msg.ContentType = 0;
                xpNotifi.Insert(msg);
            }
        }
        catch (Exception ex)
        {
        }
        Response.Redirect("SupplierInquery.aspx");
       
    }

    protected void rRatingFromBuyer_Rate(object sender, EventArgs e)
    {
        UpdateBinaryRatingLabel();
    }

    private void UpdateBinaryRatingLabel()
    {
        //rRatingFromBuyer.Text = "Rating: " + rRatingFromBuyer.Value.ToString();

        if (rRatingFromBuyer.Value < 0)
        {
            rRatingFromBuyer.ForeColor = System.Drawing.Color.Red;
        }
        else
        {
            rRatingFromBuyer.ForeColor = System.Drawing.Color.Green;
        }
    }

}